package com.java202411.contoller.project;

import com.auth0.jwt.JWT;

import com.java202411.contoller.authorization.AuthorizationOfficer;
import com.java202411.contoller.authorization.RequireAuthorization;
import com.java202411.contoller.commons.RoleConstant;
import com.java202411.contoller.project.request.ProjectCreateRequest;
import com.java202411.entity.UserEntity;
import com.java202411.entity.project.ProjectEntity;
import com.java202411.service.project.ProjectService;
import com.java202411.service.user.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Optional;


@RestController
@RequiredArgsConstructor
public class ProjectController {
    private final ProjectService projectService;
    private final UserService userService;

    @PostMapping("/projects")
    @RequireAuthorization(needRole = RoleConstant.TEACHER_ROLE)
    public ProjectEntity createProject(@RequestBody ProjectCreateRequest request) {

        String accessToken = AuthorizationOfficer.getAccessToken();
        String email = JWT.decode(accessToken).getClaim("email").asString();

        Optional<UserEntity> user = userService.findByEmail(email);

        if (user.isPresent()) {
            return projectService.createProject(
                    user.get().getId(),
                    request.getName(),
                    request.getDescription(),
                    request.getFileIds()
            );
        } else {
            throw new RuntimeException("用户不存在");
        }
    }

    @GetMapping("/projects")
    @RequireAuthorization
    public List<ProjectEntity> queryProjects() {
        return projectService.queryAllProject();
    }
}